import { defineComponent, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import styles from "./productAdd.module.less";
import { FileOutlined, LoadingOutlined, PlusOutlined, UploadOutlined } from "@ant-design/icons-vue";
import RichEdit from "@/components/RichEdit/RichEdit.vue";
import to from "await-to-js";
import { $upload } from "@/apis/common/upload/upload";
import { $AddProduct, $productCateListTree, $productDetail, $productUpdate } from "@/apis/product/product";
import { message } from "ant-design-vue";
import { useStore as useTagsStore } from "@/store/tags";
import eventBus from "@/common/eventBus/mitt";


export default defineComponent({
  name: 'productAdd',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const formRef = ref(null as any);
    const richEditRef = ref(null as any);
    const editing = ref(false);
    const tagsStore = useTagsStore();
    const state = reactive({
      type: route.query.type || '',
      title: '添加产品',
      form: {
        id: route.query.id || null,
        chineseName: null,  //产品名称
        englishName: null, //产品英文名称
        cateId: null,  //分类id
        image: null,  //产品图片
        setupVideo: null, //安装视频
        richText: '', //产品信息
        sort: null,
        status: 0,
      },
      cateList: [],
      file_loading: false,
    } as any);

    //url转blob
    const urlToBlob = async (url) => {
      try {
        const response = await fetch(url);
        const blob = await response.blob();
        return blob;
      } catch (error) {
        return null;
      }
    }
    //blob转字符串
    const blobToString = async (blob) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsText(blob);
      });
    }
    //获取详情
    const getDetail = async () => {
      const [err, res]: any = await to($productDetail(state.form.id))
      if (!err) {
        state.form.chineseName = res?.data?.data?.chineseName || '';
        state.form.englishName = res?.data?.data?.englishName || '';
        state.form.cateId = res?.data?.data?.cateId || '';
        state.form.image = res?.data?.data?.image || '';
        state.form.setupVideo = res?.data?.data?.setupVideo || '';
        let blob = await urlToBlob(res?.data?.data?.richText);
        let content = await blobToString(blob);
        state.form.richText = content;
        state.form.sort = res?.data?.data?.sort || '';
        state.form.status = res?.data?.data?.status || 0;
      }
    }
    //手动上传(产品图片)
    const imageUpload = async (file) => {
      const formData = new FormData();
      formData.append("file", file);
      const [err, res]: any = await to($upload(formData))
      if (err) {
        return
      }
      message.success('上传图片成功');
      state.form.image = res?.data?.ossUpload?.fileUrl;
      return false;
    }

    //手动上传(视频)
    const videoUpload = async (file) => {
      state.file_loading = true;
      const formData = new FormData();
      formData.append("file", file);
      const [err, res]: any = await to($upload(formData))
      if (err) {
        return
      }
      message.success('上传视频成功');
      state.form.setupVideo = res?.data?.ossUpload?.fileUrl;
      state.file_loading = false;
      return false
    }
    const submit = async () => {
      const blob = new Blob([state.form.richText], { type: "text/plain" })
      // 转换为 File 对象
      const file = new File([blob], "question.txt", {
        type: "text/plain",
        lastModified: new Date().getTime(),
      });
      const Form = new FormData();
      Form.append('file', file)
      const [errU, resU]: any = await to($upload(Form));
      if (errU) {
        return;
      }
      state.form.richText = resU?.data?.ossUpload?.fileUrl || '';
      const [err, res]: any = await to((state.type === 'add' ? $AddProduct : $productUpdate)(state.form))
      if (!err) {
        message.success('操作成功');
        eventBus.productFinish.emit();
        tagsStore.removeTagSimple(route.name);
        router.go(-1);
      }
    }
    const getListTree = async () => {
      const [err, res]: any = await to($productCateListTree())
      if (!err) {
        state.cateList = res.data?.data || [];
      }
    }
    onMounted(async () => {
      await getListTree();
      if (route.query.type === 'add') {
        state.title = '添加产品';
      } else {
        state.title = '编辑产品';
        await getDetail()
      }
      richEditRef?.value?.initValueHtml(
        state.form.richText || ""
      );
    })
    return () => (
      <div class={styles.productAdd}>
        <div class={styles.card}>
          <div class={styles.title}>{state.title}</div>
          <div class={styles.container}>
            <div class={styles.formBox}>
              <a-form style={{ width: "100%" }} ref={formRef} model={state.form} label-col={{ style: { width: '130px', marginRight: '10px' } }} wrapper-col={{ span: 18 }}>
                <a-form-item label="产品名称" name="chineseName">
                  <a-input v-model:value={state.form.chineseName} placeholder="请输入产品名称" />
                </a-form-item>
                <a-form-item label="产品英文名称" name="englishName">
                  <a-input v-model:value={state.form.englishName} placeholder="请输入产品英文名称" />
                </a-form-item>
                <a-form-item label="分类名称" name="cateId">
                  <a-tree-select
                    v-model:value={state.form.cateId}
                    tree-data={state.cateList}
                    placeholder="请选择分类"
                    fieldNames={{
                      label: 'name', value: 'id', children: 'children'
                    }}
                  ></a-tree-select>
                </a-form-item>
                <a-form-item label="产品图片" name="image">
                  <div class={styles.imgBox}>
                    {
                      state.form.image && <img src={state.form.image} />
                    }
                    <a-upload
                      before-upload={(file) => imageUpload(file)}
                      showUploadList={false}
                      name="file"
                    >
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon} />
                      </div>
                    </a-upload>
                  </div>
                </a-form-item>
                <a-form-item label="安装视频" name="setupVideo">
                  <div class={styles.videoBox}>
                    <a-upload
                      // file-list={state.form.setupVideo ? [state.form.setupVideo] : []}
                      before-upload={(file) => videoUpload(file)}
                      maxCount={1}
                      name="file"
                      show-upload-list={false}
                    >
                      <a-button>
                        {state.file_loading ? <LoadingOutlined /> : <UploadOutlined />}
                        上传文件
                      </a-button>
                    </a-upload>
                    <div class={styles.file}>
                      <FileOutlined />
                      <span class={styles.fileNameBox}>
                        {state.form.setupVideo ? <span class={styles.fileName}>{state.form.setupVideo}</span> : <span class={styles.noFile}>暂未上传</span>}
                      </span>
                    </div>
                  </div>
                </a-form-item>
                <a-form-item label="产品信息" name="richText">
                  <div class={styles.richEditBox}>
                    <RichEdit ref={richEditRef} v-model={state.form.richText} />
                  </div>
                </a-form-item>
                <a-form-item label="排序" name="sort">
                  <a-input-number min={0} v-model:value={state.form.sort} placeholder="请输入排序" />
                </a-form-item>
                <a-form-item label="状态" name="sort">
                  <a-radio-group
                    v-model:value={state.form.status}
                    name="radioGroup"
                  >
                    <a-radio value={0}>开启</a-radio>
                    <a-radio value={1}>关闭</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-form>
            </div>
            <div class={styles.footer}>
              <a-button type="primary" loading={editing.value} onClick={() => { submit() }}>确定</a-button>
              <a-button onClick={() => { router.go(-1) }} style={{ marginLeft: '20px' }}>返回</a-button>
            </div>
          </div>
        </div>
      </div>
    )
  }
})